<script setup>
import { ref, onMounted, toRefs } from 'vue'
import FeedBack from './component/FeedBack.vue'
import CloseClient from './component/CloseClient.vue'
import QuitLogin from './component/QuitLogin.vue'
import HeaderMenu from './component/HeaderMenu.vue'
import { queryProviderList, outLogin, queryGameList, queryGameCategory } from '@/api/user'
import bgGame from '@/assets/images/bg-game-1.jpg'
import visitorLogin from '@/utils/visitor'
import { appList } from '@/config/game'
import mitt from '@/mitt'
import { Search, Refresh, CaretBottom } from '@element-plus/icons-vue'
import noLogin from '@/assets/images/no-login.png'
import autoUser from '@/assets/images/auto-user.png'
import useGameStore from '@/pinia/gameStore'
import useUserStore from '@/pinia/userInfo'
import { useRouter } from 'vue-router'
import UserLogin from './component/UserLogin.vue'
const isDrag = ref(!!window.localStorage.getItem('is_drag'))
const userStore = useUserStore()
const gameStore = useGameStore()
const { searchKeys } = toRefs(gameStore)
const { currentGameType } = toRefs(gameStore)
const { token, userInfo, showLoginDialog, currentProvider } = toRefs(userStore)
const showQuitDialog = ref(false)
const placeKey = ref('请输入关键字搜索')
const searchKey = ref('')
const router = useRouter()
const provideList = ref([])
const gameTypeList = ref([])
const isMacLogin = ref(true)
const isClient = window.electronAPI || window.__TAURI__
let last_id = ''
onMounted(() => {
  _queryProviderList()
  // 加载更多游戏
  mitt.on('loadMore', () => {
    _getGameList()
  })
  visitorLogin((tag) => {
    // 判断账号是否登录成功
    isMacLogin.value = tag
    if (!tag && !window.localStorage.getItem('userLogin')) {
      userStore.setState({
        userInfo: {},
        token: ''
      })
    }
  })
})

// 查询游戏分类
const allType = {
  label: '',
  name: '全部游戏'
}

// 刷新应用
const refreshPage = () => {
  //changeGameType(currentGameType.value)
  window.location.reload()
}

const getGameType = async () => {
  const { data } = await queryGameCategory({
    provider_id: currentProvider.value.provider_id,
    status: 0
  })
  gameTypeList.value = [allType].concat(data.list)
  if (!currentGameType.value.label) {
    gameStore.setState({
      currentGameType: allType
    })
  }
  _getGameList()
}

// 查询供应商列表
let gameList = []
const _queryProviderList = async () => {
  const { data } = await queryProviderList({
    status: 0
  })
  provideList.value = data.list || []
  if (data.list && data.list.length > 0) {
    const provider_id = data.list[0].provider_id
    const provider_name = data.list[0].name
    userStore.setState({
      currentProvider: {
        provider_id,
        provider_name
      }
    })
    getGameType()
  }
}

// 切换供应商
const changeProvider = (provider_id, provider_name) => {
  searchKey.value = ''
  userStore.setState({
    currentProvider: {
      provider_id,
      provider_name
    }
  })
  last_id = ''
  gameStore.setState({
    currentGameType: allType
  })
  getGameType()
}

// 获取游戏列表
const _getGameList = async (name = '') => {
  gameStore.setState({
    isMore: true
  })
  const result = await queryGameList({
    provider_id: currentProvider.value.provider_id,
    status: 0,
    name,
    label: currentGameType.value.label,
    last_id,
    size: 60
  })
  if (!last_id) {
    gameList = result.data.list || []
  } else {
    gameList = gameList.concat(result.data.list || [])
  }
  last_id = result.data.last_id
  if (gameList.length > 0 && name) {
    searchKeys.value.unshift(searchKey.value)
    gameStore.setState({
      searchKeys: [...new Set(searchKeys.value)]
    })
  }
  gameStore.setState({
    gameList,
    isMore: result.data.more
  })
}

// 切换游戏分类
const changeGameType = (item) => {
  searchKey.value = ''
  if (!item.path) {
    gameStore.setState({
      currentGameType: item
    })
    last_id = ''
    _getGameList()
  } else {
    if (!token.value) {
      showLoginDialog.value = true
      return
    } else {
      gameStore.setState({
        currentGameType: item
      })
    }
  }
  document.querySelector('#game-list').scrollTo(0, 0)
  router.push(item.path || '/')
}
// 弹出登录框
const showLogin = () => {
  showLoginDialog.value = true
}
// 退出登录
const loginOut = async () => {
  try {
    await outLogin()
    changeGameType(allType)
  } catch (err) {
    console.log(err)
  }
  userStore.setState({
    userInfo: {},
    token: ''
  })
}

// 清空搜索历史和搜索游戏
const clearGame = () => {
  gameStore.setState({
    searchKeys: []
  })
}

const chooseSearch = (gameName) => {
  searchKey.value = gameName
  last_id = ''
  _getGameList(gameName)
}

// 文本框输入搜索
const searchInput = () => {
  if (window.timer) clearTimeout(window.timer)
  window.timer = setTimeout(() => {
    searchGame()
  }, 800)
}
const searchGame = () => {
  last_id = ''
  _getGameList(searchKey.value)
}

// 打开openTools
const openTools = () => {
  if (window.electronAPI) {
    window.electronAPI.sendMessage({
      type: 'openTools'
    })
  }
}

// 打开客户端
const openClient = () => {
  alert(2)
}
</script>
<template>
  <div class="console-page">
    <!--退出登录确认框-->
    <quit-login v-model="showQuitDialog" v-if="showQuitDialog" @quitLogin="loginOut"></quit-login>
    <!--视频背景-->
    <video
      src="https://start.gtimg.com/act/video/pcweb_banner_1705315316.mp4"
      :poster="bgGame"
      muted
      autoplay
      loop
      v-if="false"
      class="object-cover h-[100vh] w-[100%] z-[-1] absolute opacity-10"
    ></video>
    <!--用户登录-->
    <user-login v-if="showLoginDialog"></user-login>
    <div class="bg-[#20222e] bg-opacity-[90%] w-[100%] h-[100vh] flex flex-col">
      <header-menu></header-menu>
      <div class="w-[100vw] header-bg">
        <close-client></close-client>
        <feed-back v-if="false"></feed-back>
        <div class="main-container h-[58px] flex items-center">
          <div :class="{ 'ml-[110px]': !isClient && false }">
            <el-popover placement="top-start" :width="240" trigger="hover" effect="dark">
              <template #reference>
                <div class="relative group">
                  <div
                    @click="searchGame"
                    class="cursor-pointer hidden group-hover:block w-[70px] text-[#fff] text-center leading-[34px] h-[34px] bg-[#00c2ff] rounded-[20px] absolute right-0 z-[10]"
                  >
                    搜索
                  </div>
                  <el-input
                    class="focus:w-[300px] transition-width duration-[600ms]"
                    :input-style="{ fontSize: '14px', width: '180px', color: '#999' }"
                    :placeholder="placeKey"
                    v-model="searchKey"
                    maxlength="10"
                    @input="searchInput"
                  >
                    <template #suffix>
                      <el-icon class="cursor-pointer">
                        <Search></Search>
                      </el-icon>
                    </template>
                  </el-input>
                </div>
              </template>
              <div class="space-y-[15px]">
                <div class="flex items-center justify-between">
                  <span>搜索历史</span>
                  <span class="text-[#666] cursor-pointer" @click="clearGame">清空</span>
                </div>
                <div class="space-y-[10px]">
                  <div
                    @click="chooseSearch(item)"
                    class="text-[#00c2ff] cursor-pointer text-opacity-70 hover:opacity-80"
                    v-for="(item, index) in searchKeys.slice(0, 6)"
                    :key="index"
                  >
                    {{ item }}
                  </div>
                  <div
                    v-if="searchKeys.length == 0"
                    class="text-center py-[10px] text-[#666] text-[14px]"
                  >
                    暂无搜索数据
                  </div>
                </div>
              </div>
            </el-popover>
          </div>
          <div class="w-[30px] h-[70px] ml-[10px]" @click="openTools"></div>
          <div
            class="flex-1 h-[60px]"
            :style="{ '-webkit-app-region': isClient ? (isDrag ? 'none' : 'none') : 'none' }"
          ></div>
          <div class="flex justify-end items-center relative">
            <!--供应商列表-->
            <div
              v-if="provideList.length > 1"
              class="rounded-[80px] bg-[#000] bg-opacity-50 h-[34px] flex items-center text-[#999] p-[0px_15px] mr-[20px]"
            >
              <el-popover effect="dark" :width="80" trigger="hover">
                <template #reference>
                  <div class="flex items-center">
                    <span class="pr-[4px] text-[13px]">{{ currentProvider.provider_name }}</span>
                    <el-icon><CaretBottom /></el-icon>
                  </div>
                </template>
                <div class="cursor-pointer text-center text-[#fff] text-opacity-50 space-y-[15px]">
                  <div
                    @click="changeProvider(item.provider_id, item.name)"
                    v-for="item in provideList"
                    :key="item.provider_id"
                    class="hover:opacity-50"
                  >
                    {{ item.name }}
                  </div>
                </div>
              </el-popover>
            </div>
            <div @click="refreshPage" class="mt-[10px] mr-[10px]" v-if="isClient">
              <el-icon class="cursor-pointer" style="color: #ccc" size="24" title="刷新">
                <Refresh></Refresh>
              </el-icon>
            </div>
            <div v-if="!isClient || !isMacLogin">
              <div
                v-if="!token"
                class="relative flex items-center cursor-pointer"
                @click="showLogin"
              >
                <img class="absolute z-[2] right-[-20px] top-[-5px]" :src="noLogin" alt="未登录" />
                <img class="size-[40px]" :src="autoUser" alt="" />
              </div>
              <div v-else class="relative flex items-center cursor-pointer">
                <el-popover effect="dark" :width="80" trigger="hover">
                  <template #reference>
                    <div class="flex items-center">
                      <img class="size-[40px]" :src="autoUser" alt="" />
                      <div class="userInfo.token pl-[8px] sub-title">{{ userInfo.name }}</div>
                    </div>
                  </template>
                  <div
                    @click="showQuitDialog = true"
                    class="cursor-pointer text-center text-[#fff] text-opacity-50"
                  >
                    退出登录
                  </div>
                </el-popover>
              </div>
            </div>
            <feed-back></feed-back>
          </div>
        </div>
      </div>
      <div class="flex-1 overflow-y-auto" id="game-list">
        <div class="main-container flex">
          <div class="con-left pt-[20px]">
            <div class="sticky top-[20px] bg-[#20222e] rounded-md">
              <div class="text-[16px] py-[10px] pl-[15px] border-b border-[#333]">游戏类型</div>
              <ul>
                <li
                  @click="changeGameType(item)"
                  :class="[
                    'sub-title cursor-pointer pl-[15px] hover:pl-[15px] transition-all',
                    { act: currentGameType.label == item.label }
                  ]"
                  v-for="(item, index) in gameTypeList"
                  :key="index"
                >
                  {{ item.name }}
                </li>
              </ul>
              <div
                v-if="!isMacLogin"
                class="text-[16px] py-[10px] pl-[15px] border-b border-[#333]"
              >
                我的应用
              </div>
              <ul v-if="!isMacLogin">
                <li
                  @click="changeGameType(item)"
                  :class="[
                    'sub-title cursor-pointer pl-[15px] hover:pl-[15px] transition-all',
                    { act: currentGameType.label === item.label }
                  ]"
                  v-for="(item, index) in appList"
                  :key="index"
                >
                  {{ item.name }}
                </li>
              </ul>
            </div>
          </div>
          <div class="con-right flex-1">
            <router-view></router-view>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped lang="scss">
.console-page {
  width: 100%;
  height: 100vh;
  position: absolute;
  filter: blur(0px);
  background-image: url('@/assets/images/big-img-bf.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  :deep(.el-input__wrapper) {
    background: rgba(0, 0, 0, 0.2);
    box-shadow: 0 0 2px #444;
    padding: 2px 20px;
    border-radius: 20px;
  }
  .header-bg {
    background: rgba(0, 0, 0, 0.2);
  }
  .logo {
    font-size: 24px;
    font-weight: bold;
    letter-spacing: 2px;
  }
  .con-left {
    width: 200px;
    margin-right: 40px;
    li {
      height: 50px;
      line-height: 50px;
      margin-bottom: 5px;
      &:hover {
        opacity: 0.8;
        color: #fff;
        background-color: rgba(255, 255, 255, 0.1);
      }
      &.act {
        color: #00c2ff;
        background-color: rgba(255, 255, 255, 0.1);
        font-weight: bold;
      }
    }
  }
}
</style>
